<template>
  <div>
    <div class="crumbs">
      <el-form ref="formInline" :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="派发日期">
          <el-date-picker clearable v-model="formInline.timeValue" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader clearable change-on-select v-model="formInline.cateIds" :options="list" :props="defaultProps" :show-all-levels="false"></el-cascader>
        </el-form-item>
        <el-form-item label="证书名称/ID">
          <el-input v-model="formInline.name" placeholder="请输入证书名称/ID" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch('formInline')">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="crumbs">
      <el-button type="primary" @click="dialogTrue">一键派发</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="create_time" label="创建时间"></el-table-column>
      <el-table-column prop="type_text" label="证书类型"></el-table-column>
      <el-table-column prop="status_text" label="状态"></el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @current-change ="handleCurrentChange"
        layout="total, prev, pager, next"
        :current-page="textData.current_page"
        :page-size="textData.per_page"
        :total="textData.total">
      </el-pagination>
    </div>
    <div style="float: right;">
      <p style="font-size: 14px; color: #666666">证书派发开始后，请勿随意进行点击操作，以免导致证书派发失败或数据异常，请耐心等待至证书派发完成！</p>
    </div>
    <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="可读的应用">
          <el-checkbox-group v-model="allow_app_read">
            <el-checkbox v-for="i in applistall" :label="i.id" :key="i.id">{{i.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="资金类型">
          <el-radio-group v-model="form.fund_type">
            <el-radio v-model="form.fund_type" label="money">人民币</el-radio>
            <!--<el-radio v-model="form.fund_type" label="currency">亚数币</el-radio>-->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资金数量" prop="fund">
          <el-input class="w500" v-model="fund" placeholder="例如 人民币(元)：200"></el-input>
        </el-form-item>
        <el-form-item label="积分数量" prop="integral">
          <el-input class="w500" v-model="form.integral" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input class="w500" v-model="form.remark" placeholder="例如 200元赠送1积分"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('form')">一键派发</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import notify from '@/tools/notify'

  export default {
    data () {
      return {
        defaultProps: {
          value: 'id',
          label: 'name',
          children: '_child'
        },
        formInline: {
          timeValue: '',
          name: '',
          cateIds: []
        },
        cateId: 0,
        dialogFormVisible: false,
        form: {
          fund_type: 'money',
          fund: 0,
          other_app_read: '',
          is_public: 0,
          integral: 1,
          remark: ''
        },
        fund: '',
        allow_app_read: [11]
      }
    },
    computed: {
      ...mapState({
        tableData: state => state.certificate.distributeList,
        textData: state => state.certificate.pageData2,
        ids: state => state.certificate.certificate_ids,
        list: state => state.goodsclass.goodsTree,
        applistall: state => state.app.all
      })
    },
    created () {
      this.distributeList()
      this.goodsClassTree()
      this.appAll()
    },
    methods: {
      // 获取不分页的应用列表
      async appAll () {
        await this.$store.dispatch('app/appAll')
      },
      // 获取商品分类树
      async goodsClassTree () {
        let payload = {
          id: 28
        }
        await this.$store.dispatch('goodsclass/goodsClassTree', payload)
      },
      async distributeList (type = 0) {
        let payload = {
          page: this.textData.current_page,
          listRows: this.textData.per_page,
          neq_distribute_time: this.$route.query.timeValue,
          keywords: this.$route.query.name,
          cate_id: this.$route.query.cateId
        }
        await this.$store.dispatch('certificate/distributeList', payload).then(res => {
          if (type === 1) {
            this.sleep(0.5)
            this.distribute(res.res.certificate_ids)
          }
        })
      },
      onSearch (formName) {
        const self = this
        self.$refs[formName].validate((valid) => {
          if (valid) {
            if (self.formInline.timeValue === '') {
              let time = new Date()
              self.formInline.timeValue = time.getFullYear() + '-' + Number(time.getMonth() + 1) + '-' + time.getDate()
            } else {
              let time = new Date(self.formInline.timeValue)
              self.formInline.timeValue = time.getFullYear() + '-' + Number(time.getMonth() + 1) + '-' + time.getDate()
            }
            if (Number(self.formInline.cateIds.length) > 0) {
              self.cateId = self.formInline.cateIds[Number(self.formInline.cateIds.length) - 1]
            } else {
              self.cateId = 0
            }
            self.$router.push({path: '/certificate/distribute', query: {timeValue: self.formInline.timeValue, cateId: self.cateId, name: self.formInline.name}})
            self.distributeList()
          }
        })
      },
      onSubmit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.form.fund_type === 'money') {
              this.form.fund = Number(this.fund) * 100
            } else {
              this.form.fund = Number(this.fund)
            }
            this.form.other_app_read = this.allow_app_read.join(',')
            this.$store.dispatch('certificate/distributeRuleAdd', this.form).then(res => {
              notify.success('派发比例保存成功，开始证书派发')
              this.dialogFalse()
            })
          }
        })
      },
      distribute (ids = []) {
        const self = this
        const data = {}
        if (ids.length > 0) {
          data.time = self.$route.query.timeValue
          data.ids = ids.join(',')
        } else {
          data.time = self.$route.query.timeValue
          data.ids = self.ids.join(',')
        }
        self.OneKeyDistribute(data)
      },
      async OneKeyDistribute (data) {
        let payload = {
          certificate_ids: data.ids,
          distribute_time: data.time
        }
        await this.$store.dispatch('certificate/OneKeyDistribute', payload).then(res => {
          this.distributeList(1)
        })
      },
      handleCurrentChange (val) {
        this.textData.current_page = val
        this.distributeList()
      },
      dialogTrue () {
        const self = this
        if (self.$route.query.timeValue === undefined || self.$route.query.timeValue === '') {
          notify.warning('请选择派发的日期, 查询相对应的证书!')
          return false
        }
        if (self.$route.query.cateId === undefined || self.$route.query.cateId === '') {
          notify.warning('请选择派发的商品分类, 查询相对应的证书!')
          return false
        }
        self.dialogFormVisible = true
      },
      dialogFalse () {
        this.dialogFormVisible = false
        this.distribute()
      }
    }
  }
</script>

<style scoped>
  .crumbs {
    display: inline-block;
    vertical-align: top;
    margin-right: 50px;
  }
</style>
